<script setup>
import { ref, reactive, watch, onMounted, h, nextTick } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useCurrentWatchStore } from '@T2/store/users.ts';
import { positionApi as MainApi, positionById as MainById } from '@T2/service/api.ts';

const emits = defineEmits(['exit-position']);

const currentWatchStore = useCurrentWatchStore();
const { curProject } = currentWatchStore;

onMounted(() => {
  GetMainTable();
});

const MainTable = reactive({
  data: [],
  total: 0,
  levelDatas: [],
  currentLevel: null,
});
const Filter = reactive({
  page: 1,
  pagesize: 30,
  search: '',
  parent: null,
});
watch(() => ({...Filter}), (nv, ov) => {
  if (nv.page === 1 || nv.page !== ov.page) {
    GetMainTable();
  } else {
    Filter.page = 1;
  }
});
const GetMainTable = () => {
  MainApi({
    method: 'get',
    params: {
      ...Filter,
      ordering: 'create_time',
      parent__isnull: Filter.parent ? null : true,
    }
  }).then(res => {
    MainTable.data = res?.results || [];
    MainTable.total = res?.count || 0;
  });
}

/* 新增编辑 */
const MainPopup = reactive({
  visible: false,
  type: '新增',
});
const MainForm = reactive({
  model: {},
});
const MainFormRef = ref(null);
const handleMainAdd = () => {
  MainPopup.visible = true;
  MainPopup.type = '新增';
  MainForm.model = {};
  nextTick(() => {
    MainFormRef.value.clearValidate();
  });
}
const handleMainEdit = (row) => {
  MainPopup.visible = true;
  MainPopup.type = '编辑';
  MainForm.model = {
    id: row.id,
    name: row.name,
    mark: row.mark,
  };
  nextTick(() => {
    MainFormRef.value.clearValidate();
  });
}
const handleMainSubmit = () => {
  MainFormRef.value.validate((valid) => {
    if (valid) {
      MainPopup.visible = false;
      if (MainPopup.type === '新增') {
        AddMain();
      } else if (MainPopup.type === '编辑') {
        EditMain();
      }
    }
  });
}
const AddMain = () => {
  MainApi({
    method: 'post',
    data: {
      ...MainForm.model,
      parent: Filter.parent,
      project: curProject.id,
    }
  }).then(res => {
    ElMessage.success('新增成功');
    GetMainTable();
  });
}
const EditMain = () => {
  MainById({
    method: 'patch',
    id: MainForm.model.id,
    data: {
      ...MainForm.model,
    }
  }).then(res => {
    ElMessage.success('编辑成功');
    GetMainTable();
  });
}
const handleMainDelete = (row) => {
  ElMessageBox.confirm('', {
    message: h('div', null,[
      h('p',{ style:'font-size:16px;color: #4C4C4C;font-weight:500;'}, `您是否要删除 ${ row.name }？`),
    ]),
    type: 'warning',
    confirmButtonText: '确认',
  }).then(() => {
    MainApi({
      method: 'get',
      params: {
        parent: row.id,
      }
    }).then(res => {
      if (res?.results.length) {
        ElMessage.error('查询到该区域下还有子区域，请先删除子区域，以免误删除！');
        return;
      }
      MainById({
        method: 'delete',
        id: row.id,
      }).then(res => {
        ElMessage.success('删除成功');
        GetMainTable();
      });
    });
  }).catch(() => {
    ElMessage.info('已取消');
  });
}

const handleNextLevel = (row) => {
  Filter.parent = row.id;
  MainTable.levelDatas.push(row);
  MainTable.currentLevel = row.id;
}
const backToSomeLevel = (item = null) => {
  if (item?.id === MainTable.currentLevel) {
    return;
  }
  if (!item) {
    Filter.parent = null;
    MainTable.levelDatas = [];
    MainTable.currentLevel = null;
  } else {
    const dex = MainTable.levelDatas.findIndex(i => i.id === item.id);
    Filter.parent = item.id;
    MainTable.levelDatas.splice(dex + 1);
    MainTable.currentLevel = item.id;
  }
}

</script>

<template>
  <div class="view flex-column">
    <div class="nav-line">
      <el-breadcrumb separator-icon="ArrowRight">
        <el-breadcrumb-item @click="emits('exit-position')">站点管理</el-breadcrumb-item>
        <el-breadcrumb-item :class="{ 'isActive': !MainTable.currentLevel }" @click="backToSomeLevel()">区域管理</el-breadcrumb-item>
        <template v-for="item in MainTable.levelDatas">
          <el-breadcrumb-item
            :class="{ 'isActive': item.id === MainTable.currentLevel }"
            @click="backToSomeLevel(item)"
          >
            {{ item.name }}
          </el-breadcrumb-item>
        </template>
      </el-breadcrumb>
    </div>
    
    <div class="position-box flex-column mainCard">
      <el-form label-width="120px" class="flex t_form">
        <el-form-item label="名称查询：">
          <el-input v-model="Filter.search" clearable></el-input>
        </el-form-item>
        <div class="flex r_btn">
          <el-button type="primary" @click="handleMainAdd()">新增</el-button>
        </div>
      </el-form>
      <el-table :data="MainTable.data" scrollbar-always-on>
        <el-table-column label="序号" type="index" min-width="80px" align="center" fixed="left"></el-table-column>
        <el-table-column label="区域名称" prop="name" min-width="200px" show-overflow-tooltip></el-table-column>
        <el-table-column label="备注" prop="mark" min-width="300px"></el-table-column>
        <el-table-column label="更新时间" prop="update_time" min-width="160px"></el-table-column>
        <el-table-column label="操作" fixed="right" align="center" min-width="200px">
          <template #default="scope">
            <el-button link type="primary" @click="handleNextLevel(scope.row)" v-if="!scope.row.parent">查看子区域</el-button>
            <el-button link type="primary" @click="handleMainEdit(scope.row)">编辑</el-button>
            <el-button link type="danger" @click="handleMainDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        layout="->, total, prev, pager, next, sizes"
        background 
        :page-sizes="[10, 20, 30, 50, 100]"
        :pager-count="5"
        v-model:currentPage="Filter.page"
        v-model:page-size="Filter.pagesize"
        :total="MainTable.total"
      />
    </div>
  </div>
  
  <!-- 新增编辑 -->
  <el-dialog width="500px" :title="MainPopup.type + '区域'" v-model="MainPopup.visible">
    <el-form
      ref="MainFormRef"
      :model="MainForm.model"
      label-width="120px"
    >
      <el-form-item prop="name" label="区域名称：" :rules="[{required: true, message: '不能为空', trigger: 'blur'},]">
        <el-input v-model="MainForm.model.name"></el-input>
      </el-form-item>
      <el-form-item prop="mark" label="备注：">
        <el-input v-model="MainForm.model.mark"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="MainPopup.visible = false">取 消</el-button>
        <el-button type="primary" @click="handleMainSubmit()">确 定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style lang="scss" scoped>
@use '@T2/styles/normal.scss';
.view {
  width: 100%;
  height: 100%;
}
.nav-line {
  height: 30px;
  padding: 12px 12px 6px;
}
.position-box {
  flex: 1;
  overflow: hidden;
  position: relative;
}
</style>

<style scoped>
:deep(.el-breadcrumb__inner) {
  cursor: pointer !important;
}
:deep(.el-breadcrumb__item.isActive .el-breadcrumb__inner) {
  color: #0079FE;
}
</style>